import glob
import re
from concurrent.futures import ThreadPoolExecutor
from compements.target_url import process_admin
import time


def main():
    # 1. 查找所有admin_n.txt文件
    admin_files = glob.glob("./文档/admin_*.txt")
    if not admin_files:
        print("未找到admin_n.txt文件")
        return False

    # 2. 提取编号n
    tasks = []
    for file in admin_files:
        match = re.search(r'admin_(\d+)\.txt', file)
        if match:
            n = match.group(1)
            tasks.append((file, n))
        else:
            print(f"忽略无效文件：{file}")

    # 3. 自适应分三批处理任务
    batches = []
    if tasks:
        batch_size = len(tasks) // 3
        remainder = len(tasks) % 3

        start_idx = 0
        for i in range(3):
            current_batch_size = batch_size + (1 if i < remainder else 0)
            end_idx = start_idx + current_batch_size

            if start_idx < len(tasks):
                batches.append(tasks[start_idx:end_idx])
                start_idx = end_idx
            else:
                break

    max_retries = 3  # 设置最大重试次数

    try:
        for batch_index, batch in enumerate(batches):
            print(f"处理批次 {batch_index + 1}")
            # 为每个任务维护重试次数
            task_retry_counts = {task: 0 for task in batch}
            failed_tasks = batch.copy()  # 初始时所有任务都待执行

            # 循环直到所有任务成功或达到最大重试次数
            while failed_tasks and any(count < max_retries for count in task_retry_counts.values()):
                current_tasks = failed_tasks.copy()
                failed_tasks.clear()

                with ThreadPoolExecutor(max_workers=min(len(current_tasks), 5)) as executor:
                    # 提交当前需要执行的任务
                    futures = {}
                    for task in current_tasks:
                        future = executor.submit(process_admin, task[0], task[1])
                        futures[future] = task

                    # 收集执行结果
                    for future in futures:
                        task = futures[future]
                        try:
                            future.result()
                            # 任务成功，重置重试计数
                            task_retry_counts[task] = 0
                        except Exception as e:
                            task_retry_counts[task] += 1
                            if task_retry_counts[task] < max_retries:
                                failed_tasks.append(task)
                                print(f"任务 {task} 第 {task_retry_counts[task]} 次执行失败: {e}，稍后重试")
                                time.sleep(1)  # 短暂延迟
                            else:
                                print(f"任务 {task} 已达到最大重试次数，执行失败: {e}")
                                return False  # 或者可以选择继续执行其他任务

        print("所有任务执行成功")
        return True

    except Exception as e:
        print(f"程序执行过程中发生异常: {e}")
        return False


def run_with_retry(max_retries=3):
    """带重试功能的程序运行函数"""
    for attempt in range(1, max_retries + 1):
        print(f"程序第 {attempt} 次运行开始")
        success = main()
        if success:
            print("程序执行成功")
            return
        else:
            if attempt < max_retries:
                print(f"程序执行失败，5秒后重新开始...")
                time.sleep(5)
            else:
                print("已达到最大重试次数，程序退出")


if __name__ == "__main__":
    run_with_retry()
